package com.buddy.zookeeper.client;

import org.apache.zookeeper.*;

import java.io.IOException;

public class Client implements Watcher {

    ZooKeeper zk;
    String hostPort;
    Client(String hostPort){
        this.hostPort = hostPort;
    }
    void startZK() throws IOException {
        zk = new ZooKeeper(hostPort,15000,this);
    }

    String queueCommand(String command) throws InterruptedException, KeeperException {
        while(true){
            try {
                String name = zk.create("/tasks/task-",
                        command.getBytes(),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL_SEQUENTIAL);
                return name;
            } catch (KeeperException.NodeExistsException e) {
                e.printStackTrace();
                break;
            }catch (KeeperException.ConnectionLossException e){
                break;
            }
        }
        return null;
    }

    public void process(WatchedEvent event) {
        System.out.println(event);
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        Client client = new Client("127.0.0.1:2181");
        client.startZK();
        String name = client.queueCommand("CMD");
        System.out.println(name);
    }
}
